<template>
  <div id="home" class="upload">
    <div class="uploadContain">
      <div class="upload-demo">
        <!-- <div class="uploadBtn">
                    <el-button @click="uploadWay = 'wj'; uploadType = 'rb'" :type="uploadWay == 'wj' ? 'primary' : ''" round
                        size="large" style="width: 100px;">文件上传</el-button>
                    <el-button @click="uploadWay = 'sg'; uploadType = 'rb'" :type="uploadWay == 'sg' ? 'primary' : ''" round
                        size="large" style="width: 100px;">手工填报</el-button>
                </div> -->
        <div class="filter">
          <div class="uploadBtn" v-if="uploadWay == 'wj'">
            <el-select
              v-model="uploadType"
              class="m-2"
              placeholder="请选择上传类型"
              size="large"
              style="width: 140px"
            >
              <el-option
                v-for="item in uploadTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div
            class="uploadBtn"
            v-if="
              (uploadType == 'rb' ||
                uploadType == 'yb' ||
                uploadType == 'scsj') &&
              localTypeUnit == 1
            "
          >
            <el-select
              v-model="typeUnit"
              class="m-2"
              placeholder="请选择上传单位"
              size="large"
              style="width: 160px"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="uploadBtn" v-if="uploadWay == 'sg'">
            <el-date-picker
              v-model="dateValue"
              type="month"
              size="large"
              style="width: 130px"
              :disabled-date="disabledDate"
              @change="dateValueChange"
            />
          </div>
          <div class="uploadBtn" v-if="uploadWay == 'wj'">
            <el-button
              @click="modelDownload(uploadType)"
              size="large"
              type="default"
              style=""
              :icon="Download"
              >{{
                uploadType == "rb"
                  ? "日报"
                  : uploadType == "yb"
                  ? "月报"
                  : "生产数据"
              }}模版下载</el-button
            >
          </div>
        </div>
        <div v-if="uploadWay == 'wj'" style="width: 100%">
          <el-upload
            drag
            action="#"
            :http-request="dailyExcelImport"
            :on-change="handleChange"
            :file-list="fileList"
            v-model="uploadList"
            accept=".xlsx,.xls"
            :on-success="
              (res) => {
                return handleExcelImportSuccess(res);
              }
            "
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text" style="margin-bottom: 20px">
              上传 <em>{{ uploadType == "rb" ? "日报" : "月报" }}</em>
            </div>
            <div class="el-upload__text">
              拖拽到这里 或者 <em>点击这里</em> 上传
            </div>
            <template #tip>
              <div class="el-upload__tip" style="line-height: 2">
                文件格式：.xlsx、.xls
              </div>
            </template>
          </el-upload>
        </div>
        <div v-else>
          <el-table
            :data="tableData"
            style="width: 100%"
            border
            :height="hHeight + 'px'"
            size="small"
          >
            <el-table-column
              prop="dateTime"
              label="日期"
              width="100"
              align="center"
            />
            <el-table-column
              prop="treatedWaterQuantity"
              label="处理水量(吨)"
              align="center"
              v-if="waterYieldType == '1'"
            >
              <template #default="scope">
                <el-input
                  :disabled="scope.row.isNoEdit"
                  v-model="scope.row.treatedWaterQuantity"
                  size="small"
                  @focus="focusFn(scope.$index, 'treatedWaterQuantity')"
                  style="width: 100%"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="waterContent"
              label="中水量(吨)"
              align="center"
              v-if="waterYieldType == '1'"
            >
              <template #default="scope">
                <el-input
                  :disabled="scope.row.isNoEdit"
                  v-model="scope.row.waterContent"
                  size="small"
                  @focus="focusFn(scope.$index, 'waterContent')"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="overflowsSewage"
              label="外溢雨污水量(吨)"
              align="center"
              v-if="typeUnit == '2' && waterYieldType == '1'"
            >
              <template #default="scope">
                <el-input
                  :disabled="scope.row.isNoEdit"
                  v-model="scope.row.overflowsSewage"
                  size="small"
                  @focus="focusFn(scope.$index, 'overflowsSewage')"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="ch3cooNa"
              label="乙酸钠(吨)"
              align="center"
              v-if="waterYieldType == '2'"
            >
              <template #default="scope">
                <el-input
                  :disabled="scope.row.isNoEdit"
                  v-model="scope.row.ch3cooNa"
                  size="small"
                  @focus="focusFn(scope.$index, 'ch3cooNa')"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="na2C2O4"
              label="复合碳源(吨)"
              align="center"
              v-if="waterYieldType == '2'"
            >
              <template #default="scope">
                <el-input
                  :disabled="scope.row.isNoEdit"
                  v-model="scope.row.na2C2O4"
                  size="small"
                  @focus="focusFn(scope.$index, 'na2C2O4')"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="pac"
              label="PAC(吨)"
              align="center"
              v-if="waterYieldType == '2'"
            >
              <template #default="scope">
                <el-input
                  :disabled="scope.row.isNoEdit"
                  v-model="scope.row.pac"
                  size="small"
                  @focus="focusFn(scope.$index, 'pac')"
                />
              </template>
            </el-table-column>
            <el-table-column prop="pac" label="操作" width="60">
              <template #default="scope">
                <!-- <el-button size="small" type="primary"
                                    @click="handleEdit(scope.$index, scope.row)">粘贴</el-button> -->
                <div v-if="scope.row.auditStatus == '0'" style="color: #ccc">
                  待审核中
                </div>
                <el-button
                  v-else
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                  >清除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="uploadBtn" style="margin-bottom: 0">
            <el-button
              @click="manualEntry"
              size="large"
              type="primary"
              style="width: 212px; margin-top: 40rem"
              >提交</el-button
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import moment from "moment";
import { onMounted, ref, nextTick, watch, onBeforeUnmount } from "vue";
import { UploadFilled, Download } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, genFileId } from "element-plus";

import Storage from "@/utils/storage.js"; // storage工具类，简单的封装
import { useRouter } from "vue-router";
import uploadHttp from "@/https/upload.js";

const props = defineProps({
  type: {
    type: String,
    default: "1",
  },
  viewType: {
    type: String,
    default: "1",
  },
  waterYieldType: {
    type: String,
    default: "1",
  },
});
const fileList = ref([]);
const uploadList = ref([]);
const uploadParam = ref({});
const localTypeUnit = ref(Storage.localGet("depId"));
const username = ref(Storage.localGet("username"));
const typeUnit = ref(Storage.localGet("depId"));
if (localTypeUnit.value == "1") {
  typeUnit.value = "2";
}
const typeUnitName = ref("");
const focusRow = ref(0);
const focusColumnName = ref("");
typeUnitName.value =
  typeUnit.value == "1"
    ? "总公司"
    : typeUnit.value == "2"
    ? "星沙厂"
    : typeUnit.value == "3"
    ? "城西厂"
    : typeUnit.value == "4"
    ? "城北厂"
    : "城南厂";
watch(typeUnit, (val) => {
  queryWater();
  typeUnitName.value =
    typeUnit.value == "1"
      ? "总公司"
      : typeUnit.value == "2"
      ? "星沙厂"
      : typeUnit.value == "3"
      ? "城西厂"
      : typeUnit.value == "4"
      ? "城北厂"
      : "城南厂";
});
let dateValue = ref(moment().format("YYYY-MM"));
const options = ref([
  // { label: '总公司', value: '1' },
  { label: "星沙厂", value: "2" },
  { label: "城西厂", value: "3" },
  { label: "城北厂", value: "4" },
  { label: "城南厂", value: "5" },
]);
const uploadWay = ref("");
const uploadType = ref("rb");
const uploadTypeList = ref([]);
if (props.viewType == "1") {
  uploadTypeList.value = [
    { label: "月报", value: "yb" },
    { label: "生产数据", value: "scsj" },
  ];
  uploadType.value = "yb";
}
if (props.viewType == "2") {
  uploadTypeList.value = [{ label: "日报", value: "rb" }];
  uploadType.value = "rb";
}
const tableData = ref([]);

const hHeight = ref(0);
const wWidth = ref(0);
const disabledDate = ref((time) => {
  return time.getTime() > Date.now();
});

const emits = defineEmits(["submitEditEmit"]);
watch(
  () => props.type,
  (val, oldVal) => {
    console.log(val, oldVal);
    if (val == "1") {
      uploadWay.value = "wj";
    } else if (val == "2") {
      uploadWay.value = "sg";
    }
  },
  { immediate: true }
);
onMounted(() => {
  // getDepIdToName()
  queryWater();
  // manualEntry()
  nextTick(() => {
    hHeight.value = document.documentElement.clientHeight - 400;
    wWidth.value = document.documentElement.clientWidth - 340;
  });
  window.addEventListener("paste", (event) => {
    event = event || window.event;
    const clipdata = event.clipboardData || window.clipboardData;
    const value = clipdata.getData("text/plain");
    console.log(value);
    let clipboardList = value.split("\r\n");
    clipboardList.forEach((item, ind) => {
      let itemList = item.split("\t");
      clipboardList[ind] = itemList;
    });
    setTimeout(() => {
      console.log("1111", clipboardList);
      let paramsList = [];
      if (typeUnit.value == "2") {
        paramsList = [
          "treatedWaterQuantity",
          "waterContent",
          "overflowsSewage",
          "ch3cooNa",
          "na2C2O4",
          "pac",
        ];
      } else {
        paramsList = [
          "treatedWaterQuantity",
          "waterContent",
          "ch3cooNa",
          "na2C2O4",
          "pac",
        ];
      }
      console.log(paramsList);
      let column = paramsList.findIndex((item) => {
        return item == focusColumnName.value;
      });
      console.log(column, paramsList);
      clipboardList.forEach((item, ind) => {
        item.forEach((n, m) => {
          n = n.replace(/\s+/g, "");
          n = n.replace(/(\r\n|\n|\r)/gm, "");
          tableData.value[focusRow.value + ind][paramsList[column + m]] = n;
        });
      });
    });
  });
});
const getDepIdToName = () => {
  uploadHttp.getDepIdToName().then((res) => {
    console.log(res);
  });
};
const handleChange = (file, fileList) => {
  console.log(file, fileList);
  uploadList.value = fileList;
  if (fileList.length > 1) {
    fileList.splice(0, 1);
  }
};

const dailyExcelImport = (params) => {
  console.log(params);
  if (uploadType.value == "rb" && !typeUnit.value) {
    ElMessage({
      message: "单位不能为空",
      type: "warning",
    });
    return;
  }
  console.log(params);
  if (uploadType.value == "rb") {
    // 日报上传
    let dataObj = {
      file: params.file,
      depId: typeUnit.value,
      username: username.value,
    };
    uploadHttp.dailyExcelImport(dataObj).then((res) => {
      console.log(res);
      if (res.data.code == 200) {
        ElMessage({
          message: "上传成功",
          type: "success",
        });
        emits("submitEditEmit");
      } else {
        fileList.value = [];
        ElMessage({
          message: "上传失败,请重新上传",
          type: "error",
        });
      }
    });
  } else if (uploadType.value == "yb") {
    // 月报上传
    let dataObj = {
      file: params.file,
      depId: typeUnit.value,
      username: username.value,
    };
    uploadHttp.monthlyExcelImport(dataObj).then((res) => {
      console.log(res);
      if (res.data.code == 200) {
        ElMessage({
          message: "上传成功",
          type: "success",
        });
        emits("submitEditEmit");
      } else {
        fileList.value = [];
        ElMessage({
          message: "上传失败,请重新上传",
          type: "error",
        });
      }
    });
  } else {
    let dataObj = {
      file: params.file,
      depId: typeUnit.value,
      username: username.value,
    };
    uploadHttp.waterYield(dataObj).then((res) => {
      console.log(res);
      if (res.data.code == 200) {
        ElMessage({
          message: "上传成功",
          type: "success",
        });
        emits("submitEditEmit");
      } else {
        fileList.value = [];
        ElMessage({
          message: "上传失败,请重新上传",
          type: "error",
        });
      }
    });
  }
};
const dateValueChange = (item) => {
  dateValue.value = item;
  console.log(moment(dateValue.value).format("YYYY-MM-DD"));
  queryWater();
};
const queryWater = () => {
  let params = {
    entryDate: moment(dateValue.value).format("YYYYMM"),
    depId: typeUnit.value,
  };
  uploadHttp.queryWater(params).then((res) => {
    console.log(res);
    res.data.data.forEach((item) => {
      // item.auditStatus = '0'
      item.dateTime = moment(item.entryDate).format("YYYY-MM-DD");
      if (
        moment(item.dateTime).valueOf() > moment().valueOf() ||
        item.auditStatus == "0"
      ) {
        item.isNoEdit = true;
      } else {
        item.isNoEdit = false;
      }
    });
    tableData.value = res.data.data;
  });
};
const manualEntry = () => {
  let confirmList = [];
  tableData.value.forEach((item) => {
    item.depId = typeUnit.value;
    if (item.auditStatus != "0") {
      confirmList.push(item);
    }
  });
  let params = {
    manualEntryDTOList: confirmList,
    username: username.value,
  };
  uploadHttp.manualEntry(params).then((res) => {
    console.log(res);
    if (res.data.code == 200) {
      ElMessage({
        message: "上传成功",
        type: "success",
      });
      queryWater();
      emits("submitEditEmit");
    } else {
      ElMessage({
        message: "上传失败,请重新上传",
        type: "error",
      });
    }
  });
};
const handleExcelImportSuccess = (res) => {
  console.log("--------", res);
};
const modelDownload = (uploadType) => {
  let http =
    uploadType == "rb"
      ? "dailyDownload"
      : uploadType == "yb"
      ? "monthlyDownload"
      : "dowmloadProduction";
  console.log(http);
  uploadHttp[http](typeUnit.value).then((response) => {
    console.log(response);
    const content = response.data;
    const blob = new Blob([content], { type: "application/ms-excel" });
    let fileName = "";
    if (uploadType == "scsj") {
      fileName = `生产数据上传模版.xls`;
    } else {
      fileName = `${typeUnitName.value}上传模版.xls`;
    }
    if ("download" in document.createElement("a")) {
      // 非IE下载
      const elink = document.createElement("a");
      elink.download = fileName;
      elink.style.display = "none";
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    } else {
      // IE10+下载
      navigator.msSaveBlob(blob, fileName);
    }
  });
};
const handleDelete = (index, row) => {
  tableData.value[index].treatedWaterQuantity = "";
  tableData.value[index].waterContent = "";
  tableData.value[index].overflowsSewage = "";
  tableData.value[index].ch3cooNa = "";
  tableData.value[index].na2C2O4 = "";
  tableData.value[index].pac = "";
};
const focusFn = (row, columnName) => {
  console.log("1111------", row, columnName);
  focusRow.value = row;
  focusColumnName.value = columnName;
};

const handleEdit = (index, row) => {
  console.log("剪切板内容:", navigator.clipboard);
  navigator.clipboard
    .read()
    .then((res) => {
      console.log("剪切板内容:", res);
      if (res) {
        let clipboardList = res.split("\r\n");
        console.log("剪切板内容:", clipboardList);
        clipboardList.forEach((item, ind) => {
          let itemList = item.split("\t");
          tableData.value[index + ind].treatedWaterQuantity = itemList[0] || "";
          tableData.value[index + ind].waterContent = itemList[1] || "";
          tableData.value[index + ind].overflowsSewage = itemList[2] || "";
          tableData.value[index + ind].ch3cooNa = itemList[3] || "";
          tableData.value[index + ind].na2C2O4 = itemList[4] || "";
          tableData.value[index + ind].pac = itemList[5] || "";
        });
      }
    })
    .catch((err) => {
      console.log("获取剪切板内容失败:", err);
    });
  // console.log(window.clipboardData)
  // document.addEventListener('paste', (event) => {
  //     event.preventDefault()
  //     console.log(1111)
  //     let paste = (event.clipboardData || window.clipboardData).getData(
  //         'text'
  //     )
  //     console.log(paste)
  // })
};
</script>
<style lang="less">
@import "@/assets/css/home.less";

.upload {
  padding-bottom: 0 !important;

  .uploadContain {
    width: 100%;

    .upload-demo {
      .filter {
        display: flex;
        flex-direction: row;
      }

      .uploadBtn {
        text-align: left;
        margin-bottom: 40rem;
        margin-right: 20rem;
      }
    }
  }
}
</style>
